<template>
    <div class="adduser">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>添加新用户</span>
                <el-button @click="$router.go(-1)" style="float: right; padding: 3px 0" type="text">返回</el-button>
            </div>
            <el-form :rules="rules" ref="addform" :label-position="labelPosition" label-width="80px" :model="adduserobj">
                <el-form-item label="用户名称" prop="username">
                    <el-input v-model="adduserobj.username"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="username">
                    <el-input v-model="adduserobj.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="adduserobj.email" placeholder="选填"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="adduserobj.mobile" placeholder="选填"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="adduserFn" type="success">添加新用户</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { postAddUserApi } from '@/api/usersapi'
export default {
    data() {
        return {
            labelPosition: 'right',
            adduserobj: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            // rules用来保存需要非空验证的数据
            rules: {
                username: [
                    { required: true, message: '用户名称必填' },
                    { max: 10, min: 5, message: '用户名必须在5~10位之间' }
                ],
                password: [
                    { required: true, message: '用户密码必填' },
                    { max: 10, min: 5, message: '密码必须在5~10位之间' }
                ]
            }
        };
    },
    methods: {
        adduserFn() {
            // 拿到的是el-form组件的对象
            // valid代表当前表单验证结果 true代表验证通过
            this.$refs.addform.validate(async valid => {
                if (valid) {
                    // 消息提示框
                    const res = await postAddUserApi(this.adduserobj)
                    if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                    this.$router.push('/Layout/users')
                }
            })
        }
    },
}
</script>

<style lang="scss" scoped></style>